#!/usr/bin/python

#-------------------------------------------------------------------------------
# Name:        autosetup
# Purpose:     assisting the user with first time setup of the server and
#              program. Creates directories, sets registry, etc.
#
# Author:      Donald L Talbert , www.bwhgaming.com
#
# Created:     25/09/2012
# Copyright:   (c) Donald L Talbert 2012
# Licence:     MIT
#-------------------------------------------------------------------------------

# Modules
import os
import logging
import subprocess
import win32api ##Platform
import urllib
import shutil
import shlex
import ConfigParser

#My Modules
import loadconfig
import updateserver

lc = loadconfig.LoadConfig()

def createDirectories():
    """
    If Directories do not exist, create them.
    """
    try:
        os.makedirs(lc.serverDirectory)
    except:
        logging.debug(lc.serverDirectory + ' or its parent directory already exists.')
    try:
        os.makedirs(lc.backupDirectory)
    except:
        logging.debug(lc.backupDirectory + ' or its parent directory already exists')
    try:
        os.makedirs(lc.updateDirectory)
    except:
        logging.debug(lc.updateDirectory + ' or its parent directory already exists')



def setRegistry(windows = True):
    """
    Use the windows api to launch DisableWindowsErrorReporting with admin priv.
    """
    if windows == True:
        win32api.ShellExecute(0, 'runas', 'DisableWindowsErrorReporting.exe', None, '', 1)


def getSteamCmd(): #Add Linux version support
    """
    Downloads Steamcmd online and moves it to the approate directory.
    """
    logging.info("Downloading updater...")

    urllib.urlretrieve("http://vds6.bwhgaming.net/app/RO2SM/steamcmd.exe", "steamcmd.exe") #Downloads file to current dir
    try:
        shutil.move("steamcmd.exe", lc.updateDirectory) # Attempts to move file but raises if it exist.
    except:
        logging.debug("Steamcmd Already Downloaded.")
    logging.info("Updater installed.")


def installServer(): #This needs to stdout dumped or it will flood the buffer. Needs to run til RE returns the right output. TOadd.
    """
    Runs the installer a couple times to make sure both the installer and server
    is properly installled.
    """
    logging.info("Installing server")
    a = updateserver.UpdateServer()
    x = 0
    while x < 3:
        updated = a.Main() #Run the updater.
        x = x + 1
    logging.info("Server installed")


def setFirstRunFalse():
    """
    Sets the First Run flag in misc.ini to false since this module should only
    be used the first time someone uses this on a server.
    """
    config = ConfigParser.RawConfigParser()
    config.add_section('Misc')
    config.set('Misc', 'first-run', False)
    with open ('misc.ini', 'w') as configfile:
        config.write(configfile)


def main():
    """
    The main method that launches the rest of the methods.
    """
    createDirectories()
    setRegistry()
    getSteamCmd()
    installServer()
    setFirstRunFalse()

if __name__ == '__main__':
    #logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] %(asctime)s - %(threadName)-10s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    #main()
    pass